<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户列表</title>
    <!--引用本地static目录下的bootstrap.min.css文件-->
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <script src="{% static 'js/vue.global.js' %}"></script>
    <script src="{% static 'js/axios.min.js' %}"></script>
    <script src="{% static 'js/pagination.js' %}"></script>
    <!--引用my-tree.js文件-->
    <script src="{% static 'js/my-tree.js' %}"></script>

</head>
<body>
{% verbatim %}

<div id="app" class="container-fluid">
  <!-- 搜索栏 -->
  <div class="border rounded p-3 mb-3">
    <form class="row g-3 align-items-center">

      <div class="col-auto">
        <input type="text" id="username" class="form-control" placeholder="请输入用户名" v-model="search.username">
      </div>
       <div class="col-auto">
         <!-- 状态下拉框 -->
        <select class="form-select"  v-model="search.status" >
          <option value="-1">全部</option>
          <option value="1">正常</option>
          <option value="0">停用</option>
        </select>
      </div>
      <div class="col-auto">
        <button type="button" class="btn btn-primary" @click="onSearch">搜索</button>
      </div>
    </form>
  </div>
  <!-- 操作栏 -->
  <div class="border rounded p-2 mb-3 d-flex align-items-center gap-2">
    <button class="btn btn-primary btn-sm" @click="openAdd">+ 新 增</button>
    <button class="btn btn-secondary btn-sm" @click="openHeaderEdit">修 改</button>
    <button class="btn btn-danger btn-sm" @click="batchDelete">批量删除</button>
    <button class="btn btn-outline-secondary btn-sm" disabled>导 入</button>
    <button class="btn btn-warning btn-sm">导 出</button>
  </div>
  <!-- 表格 -->
  <div class="rounded p-2">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th scope="col"><input type="checkbox" v-model="selectAll" @change="toggleAll"></th>
          <th scope="col">ID</th>
          <th scope="col">用户名</th>
          <th scope="col">用户昵称</th>
          <th scope="col">邮箱</th>
          <th scope="col">手机号</th>
          <th scope="col">状态</th>
          <th scope="col">创建时间</th>
          <th scope="col">操作栏</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td><input type="checkbox" v-model="item.selected"></td>
          <td>{{ item.id }}</td>
          <td>{{ item.username }}</td>
          <td>{{ item.real_name }}</td>
  
          <td>{{ item.email }}</td>
          <td>{{ item.phone }}</td>
          <td>
            <span v-if="item.status == 1" class="badge bg-primary">正常</span>
            <span v-else-if="item.status == 0" class="badge bg-danger">停用</span>
          </td>
          <td>{{ item.create_time }}</td>

          <td>
            <!---改成button,修改-->
            <button class="btn btn-primary btn-sm" @click="openEdit(item)">修 改</button> &nbsp;
            <!---改成button,删除,颜色为灰色-->
            <button class="btn btn-warning btn-sm" @click="openPermissionAdd(item)">授 权</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- 编辑用户弹窗 -->
  <div class="modal fade" :class="{show: modalInfo.visible}" tabindex="-1" :style="modalInfo.visible ? 'display:block;background:rgba(0,0,0,0.2);' : ''">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">{{modalInfo.title}}</h5>
          <button type="button" class="btn-close" @click="closeModal"></button>
          <!--异常显示区域-->
          <div class="alert alert-danger" v-if="modalInfo.errorMsg" role="alert">
            {{modalInfo.errorMsg}}
          </div>
        </div>
        <div class="modal-body">
          <form class="container-fluid">
            <div class="row mb-3">
              <label class="col-2 col-form-label text-end">用户名</label>
              <div class="col-3">
                <input type="text" class="form-control modal-input" v-model="dataRow.username">
              </div>
              <label class="col-3 col-form-label text-end">用户昵称</label>
              <div class="col-3">
                <input type="text" class="form-control modal-input" v-model="dataRow.real_name">
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label text-end">手机号码</label>
              <div class="col-3">
                <input type="text" class="form-control modal-input" v-model="dataRow.phone">
              </div>
              <label class="col-3 col-form-label text-end">邮箱</label>
              <div class="col-3">
                <input type="email" class="form-control modal-input" v-model="dataRow.email">
              </div>
            </div>
            <div class="row mb-3">
               <label class="col-2 col-form-label text-end">状态</label>
              <div class="col-3 d-flex align-items-center">
                <div class="form-check me-3">
                  <input class="form-check-input"  type="radio"  name="status" value="1"  v-model="dataRow.status" id="status-normal">
                  <label class="form-check-label" for="status-normal">正常</label>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="radio" name="status" value="0" v-model="dataRow.status" id="status-stop">
                  <label class="form-check-label" for="status-stop">停用</label>
                </div>

              </div>
              <label class="col-3 col-form-label text-end">用户密码</label>
              <div class="col-3">
                <input type="password" class="form-control modal-input" v-model="dataRow.password">
              </div>
            </div>

            <div class="row mb-3">
              <label class="col-2 col-form-label text-end">岗位名称</label>
              <div class="col-3">
                <input type="email" class="form-control modal-input" v-model="dataRow.job_name">
              </div>
              <label class="col-3 col-form-label text-end">用户级别</label>
              <div class="col-3">
                <select class="form-select modal-input" v-model="dataRow.is_admin">
                  <option value="0">普通用户</option>
                  <option value="1">管理员</option>
                </select>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label text-end">备注</label>
              <div class="col-9">
                <textarea class="form-control modal-input-50" rows="2" v-model="dataRow.remark" placeholder="请输入内容"></textarea>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button v-if="modalInfo.winType==='edit'" type="button" class="btn btn-primary" @click="updateRow">确 定</button>
          <button v-if="modalInfo.winType==='add'" type="button" class="btn btn-primary" @click="addRow">新 增</button>
          <button type="button" class="btn btn-light" @click="closeModal">取消</button>
        </div>
      </div>
    </div>
  </div>

  <!--授权弹出框-->
  <div class="modal fade" :class="{show: modalInfo2.visible}" tabindex="-1" :style="modalInfo2.visible ? 'display:block;background:rgba(0,0,0,0.2);' : ''">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">用户授权</h5>
          <button type="button" class="btn-close" @click="closeModal"></button>
          <!--异常显示区域-->
        </div>
        <div class="modal-body">
          <form class="container-fluid">
            <div class="row mb-3">
              <label class="col-2 col-form-label text-end">用户账号</label>
              <div class="col-3">
                <input type="text" class="form-control modal-input" disabled v-model="dataRow.username">
              </div>
              <label class="col-3 col-form-label text-end">用户昵称</label>
              <div class="col-3">
                <input type="text" class="form-control modal-input" disabled  v-model="dataRow.real_name">
              </div>
            </div>
              <div class="row mb-3">
              <label class="col-2 col-form-label text-end">授权角色</label>
              <div class="col-9">
                  <div class="tree-container" ref="treeContainer">
                        <tree-node-select
                            v-for="node in treeData"
                            :key="node.id"
                            :node="node">
                        </tree-node-select>
                    </div>
              </div>
            </div>


          </form>
        </div>
        <div class="modal-footer">
          <button type="button"   class="btn btn-primary" @click="saveUserRole">授 权</button>
          <button type="button" class="btn btn-light" @click="closeModal">取消</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
const { createApp, ref, reactive,onMounted } = Vue;
const app = createApp({
  setup() {
    const search = reactive(
    { username: '' ,
      status: -1}
    );
    const selectAll = ref(false);
    // 数据体，界面显示的元素
    const data=reactive([
    ]);
    // 列表行数据
    const dataRow=reactive({
      id: '',
      username: '',
      real_name: '',
      is_admin: 0,
      email: '',
      phone: '',
      status: 1,
      job_name: '',
      remark: '',
      role_name: '',
      role_key: ''
    });
    // 模态框信息
   const modalInfo = reactive({
      visible: false,
      title: '新增用户',
      winType:'add',//'add','edit',
      errorMsg:''
    })
    const modalInfo2 = reactive({
      visible: false,
      title: '用户授权',
      winType:'add',//'add','edit',
      errorMsg:''
    })
    
    // 树形数据结构
    const treeData = reactive([
      // 这里可以添加初始的树形结构数据
      // 例如: {id: 1, name: '权限1', children: [{id: 11, name: '子权限1'}]}
    ]);

    const toggleAll = () => {
      data.forEach(row => {
        row.selected = selectAll.value
        console.log("====>u.selected --row:",row);
      });
    };

    // 加载用户
    const queryList = () => {
      axios({
        method: 'get',
        url: '/demo/user/list/',
        params:search
      }).then(res => {
        if (res.status === 200) {
          console.log("data:",res.data.data);
          data.splice(0, data.length, ...res.data.data);
        }
      })
    }
    // 更新用户信息
    const updateRow = () => {
      axios({
        method: 'post',
        url: '/demo/user/modify/',
        data: dataRow
      }).then(res => {
        result = res.data;
        if (result.code === 200) {
         //关闭弹窗
          closeModal();
          console.log("data:",res.data);
          queryList();
        }else{
         // 提示报错
          modalInfo.errorMsg=result.msg
        }
      })
    }

    // 增加用户信息
    const addRow = () => {
      axios({
        method: 'post',
        url: '/demo/user/add/',
        data: dataRow
      }).then(res => {
        result = res.data;
        if (result.code === 200) {
                //关闭弹窗
                closeModal();
                console.log("data:",res.data);
                queryList();
        }else{
                 // 提示报错
                modalInfo.errorMsg=result.msg
        }
      })
    }


    const deleteRow = (row) => {
      console.log("deleteRow:",row);
      // 弹出确认框
      if (confirm("确定删除吗？")) {
        axios({
          method:'get',
          url:'/demo/user/delete/',
          params:{
            id:row.id
          }
        }).then(res => {
          result = res.data;
          if (result.code === 200) {
            //提示删除成功
            alert("删除成功");
            queryList();
          }
        })
      }
    }

    // 批量删除
    const batchDelete = () => {
      console.log("batchDelete:");
      // 弹出确认框
      if (confirm("确定删除吗？")) {
        // 遍历data,找到selected为true的行
        let ids = [];
        data.forEach(row => {
          if (row.selected) {
            ids.push(row.id)
          }
        })
        console.log("ids:",ids);
        if (ids.length > 0) {
          axios({
            method:"post",
            url:"/demo/user/batch_delete/",
            data:{
              ids:ids
            }
          }).then(res => {
            result = res.data;
            if (result.code === 200) {
              //提示删除成功
              alert("删除成功");
              queryList();
            }
          })
        }else{
          alert("请选择要删除的行");
        }
      }
    }

    /**用户授权角色查询*/
    const queryUserRole = (dataRow) => {
      axios({
        method: 'get',
        url: '/demo/user/role_tree/',
        params: {
          user_id: dataRow.id
        }
      }).then(res => {
        if (res.status === 200) {
          console.log("data:", res.data.data);
          treeData.splice(0, treeData.length, ...res.data.data);
        }
      })
    }

    /**用户授权角色保存*/
    const saveUserRole = () => {
      // 遍历treeData,找到checked为true的行
      let role_ids = [];
      treeData.forEach(node => {
        if (node.checked) {
          role_ids.push(node.id)
        }
      })
      console.log("role_ids:",role_ids);
      if (role_ids.length > 0) {
        axios({
          method: 'post',
          url: '/demo/user/role_update/',
          data: {
            user_id: dataRow.id,
            role_ids: role_ids
          }
        }).then(res => {
          result = res.data;
          if (result.code === 200) {
            //提示删除成功
            alert("授权成功");
            closeModal();
            queryList();
          }
        })


      }

    }


    const showModal = ref(false);

    //const editUser = reactive({});
    const onSearch = () => {
      // 模拟搜索
      console.log("search:",search);
      queryList();
    };

    const openHeaderEdit = () => {
        count=0;
        // 遍历data,找到selected为true的行
        data.forEach(r => {
          if (r.selected) {
            row=r;
            count++;
          }
        })
        if (count <= 0) {
          alert("请选择要修改的行");
        }else if(count > 1){
          alert("只能选择一行进行修改");
        }else{
          openEdit(row);
        }
    }

    const openEdit = (row) => {
      //Object.assign(dataRow, row);
      // 头部的修改

      //row复制dataRow存在的属性
      for (const key in row) {
        if (dataRow.hasOwnProperty(key)) {
          dataRow[key] = row[key];
        }
      }
      console.log("====dataRow:",dataRow);
      //showModal.value = true;
      modalInfo.visible = true;
      modalInfo.title = '编辑用户';
      modalInfo.winType = 'edit';
      modalInfo.errorMsg=''
      setTimeout(() => {
        document.body.classList.add('modal-open');
      }, 10);
    };



    const openAdd = (row) => {

      //dataRow数据初始化
      for (const key in dataRow) {
       if (key === 'is_admin') {
         dataRow[key] = 0;
       }
       else if(key === 'status'){
         dataRow[key] = 1;
        }else{
         dataRow[key] = '';
        }

      }
      console.log("====dataRow:",dataRow);
      //showModal.value = true;
      modalInfo.visible = true;
      modalInfo.title = '新增用户';
      modalInfo.winType = 'add';
      modalInfo.errorMsg=''
      setTimeout(() => {
        document.body.classList.add('modal-open');
      }, 10);
    };
    const closeModal = () => {
      //showModal.value = false;
      modalInfo.visible = false;
      modalInfo2.visible = false;  // 添加关闭授权弹窗
      setTimeout(() => {
        document.body.classList.remove('modal-open');
      }, 200);
    };
    /**打开授权框*/
    const openPermissionAdd = (row) => {
      //row复制dataRow存在的属性
      for (const key in row) {
        if (dataRow.hasOwnProperty(key)) {
          dataRow[key] = row[key];
        }
      }

      console.log("====dataRow:",dataRow);
      modalInfo2.visible = true;
      modalInfo2.title = '用户授权';
      modalInfo2.winType = 'add';
      //查询角色
      queryUserRole(row);

      setTimeout(() => {
        document.body.classList.add('modal-open');
      }, 10);
    };
    onMounted(() => {
      console.log("=====onMounted");
      queryList();
    });

    /* 返回结果，暴露外面使用 */
    return {
      search,
      data,
      selectAll,
      toggleAll,
       showModal,
      // editUser,
       openEdit,
       closeModal,
       queryList,
       onSearch,
       dataRow,
       updateRow,
       openAdd,
       modalInfo,
       addRow,
       deleteRow,
       batchDelete,
       openHeaderEdit,
       modalInfo2,openPermissionAdd,
       treeData, // 暴露treeData
       queryUserRole,
       saveUserRole,

     };

  }


});
app.mount('#app');
// 注册树形节点选择组件
registerTreeNodeSelect(app);
</script>

<style>
    /* 移除红色边框样式 */
    .modal {
      transition: opacity 0.2s;
    }
    .modal.show {
      opacity: 1;
      pointer-events: auto;
    }
    .modal:not(.show) {
      opacity: 0;
      pointer-events: none;
    }
    .modal-backdrop {
      display: none;
    }
    /* 调整弹出框宽度为650px，更协调 */
    .modal-dialog {
      max-width: 650px;
      transform: scale(0.9);
    }

    /*修改弹出框中的输入框为自动*/
    .modal-input {
      width: auto;
      min-width: 0;
    }
</style>

</body>
  {% endverbatim %} <!-- 添加此行 -->
</html>
